
 <!DOCTYPE HTML>
<html >
<head>
  <meta charset="UTF-8">
  
    <title>并发扣减库存方案二 | Typhoon&#39;s code space</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="typhoon">
    

    
    <meta name="description" content="上一篇&amp;lt;&amp;lt;并发扣减库存方案一&amp;gt;&amp;gt;中使用了基于CAS和幂等思想,使用当前值和期望值比较以及版本号变更比较来完成并发场景下 控制库存不被少扣或者扣减成负值, 此篇幅使用另外一个思路解决并发修改库存的问题,利用redis单线程阻塞操作特性,以及redis执行lua脚本原子性,来完成控制 并发场景下库存扣减问题;首先简单 介绍一下此方案用到的一些redis和lua的特性:">
<meta name="keywords" content="并发">
<meta property="og:type" content="article">
<meta property="og:title" content="并发扣减库存方案二">
<meta property="og:url" content="http://scorpioaeolus.oschina.io/2017/07/12/并发扣减库存方案二/index.html">
<meta property="og:site_name" content="Typhoon&#39;s code space">
<meta property="og:description" content="上一篇&amp;lt;&amp;lt;并发扣减库存方案一&amp;gt;&amp;gt;中使用了基于CAS和幂等思想,使用当前值和期望值比较以及版本号变更比较来完成并发场景下 控制库存不被少扣或者扣减成负值, 此篇幅使用另外一个思路解决并发修改库存的问题,利用redis单线程阻塞操作特性,以及redis执行lua脚本原子性,来完成控制 并发场景下库存扣减问题;首先简单 介绍一下此方案用到的一些redis和lua的特性:">
<meta property="og:updated_time" content="2017-07-12T15:45:34.996Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="并发扣减库存方案二">
<meta name="twitter:description" content="上一篇&amp;lt;&amp;lt;并发扣减库存方案一&amp;gt;&amp;gt;中使用了基于CAS和幂等思想,使用当前值和期望值比较以及版本号变更比较来完成并发场景下 控制库存不被少扣或者扣减成负值, 此篇幅使用另外一个思路解决并发修改库存的问题,利用redis单线程阻塞操作特性,以及redis执行lua脚本原子性,来完成控制 并发场景下库存扣减问题;首先简单 介绍一下此方案用到的一些redis和lua的特性:">

    
    <link rel="alternative" href="/atom.xml" title="Typhoon&#39;s code space" type="application/atom+xml">
    
    
    <link rel="icon" href="/typhoon/img/java.png">
    
    
    <link rel="apple-touch-icon" href="/typhoon/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/typhoon/img/jacman.jpg">
    
    <link rel="stylesheet" href="/typhoon/css/style.css">
</head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/typhoon/"><img src="/typhoon/img/java.png" alt="Typhoon&#39;s code space" title="Typhoon&#39;s code space"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/typhoon/" title="Typhoon&#39;s code space">Typhoon&#39;s code space</a></h1>
				<h2 class="blog-motto"></h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/typhoon/">主页</a></li>
					
						<li><a href="/typhoon/archives">归档</a></li>
					
						<li><a href="/typhoon/about">关于</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:scorpioaeolus.oschina.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/typhoon/2017/07/12/并发扣减库存方案二/" title="并发扣减库存方案二" itemprop="url">并发扣减库存方案二</a>
  </h1>
  <p class="article-author">By
       
		<a href="/typhoon/about" title="typhoon" target="_blank" itemprop="author">typhoon</a>
		
  <p class="article-time">
    <time datetime="2017-07-12T15:05:12.000Z" itemprop="datePublished"> Published 2017-07-12</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-redis阻塞操作"><span class="toc-number">1.</span> <span class="toc-text">1.redis阻塞操作</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-lua原子特性"><span class="toc-number">2.</span> <span class="toc-text">2.lua原子特性</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#背景"><span class="toc-number"></span> <span class="toc-text">背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#存在问题"><span class="toc-number"></span> <span class="toc-text">存在问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#案例分析"><span class="toc-number"></span> <span class="toc-text">案例分析</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#解决方案"><span class="toc-number"></span> <span class="toc-text">解决方案</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#以下是代码和并发测试"><span class="toc-number"></span> <span class="toc-text">以下是代码和并发测试</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-数据库表依赖上一篇"><span class="toc-number">1.</span> <span class="toc-text">1.数据库表依赖上一篇</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-编写接口及实现"><span class="toc-number">2.</span> <span class="toc-text">2.编写接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-单元测试"><span class="toc-number">3.</span> <span class="toc-text">3.单元测试</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#用20个线程跑了多次-状态良好-欢迎各位大佬指点和拍砖"><span class="toc-number"></span> <span class="toc-text">用20个线程跑了多次,状态良好,欢迎各位大佬指点和拍砖</span></a>
		
		</div>
		
		<pre><code>上一篇&lt;&lt;并发扣减库存方案一&gt;&gt;中使用了基于CAS和幂等思想,使用当前值和期望值比较以及版本号变更比较来完成并发场景下
控制库存不被少扣或者扣减成负值,
此篇幅使用另外一个思路解决并发修改库存的问题,利用redis单线程阻塞操作特性,以及redis执行lua脚本原子性,来完成控制
并发场景下库存扣减问题;首先简单
介绍一下此方案用到的一些redis和lua的特性:
</code></pre><a id="more"></a>
<h5 id="1-redis阻塞操作"><a href="#1-redis阻塞操作" class="headerlink" title="1.redis阻塞操作"></a>1.redis阻塞操作</h5><pre><code>鉴于redis自身独有特性,我们知道redis执行命令是阻塞操作(单进程单线程),举例说明:A服务向redis发送了两条指令,
redis.call(&apos;get&apos;,age)和redis.call(&apos;incr&apos;,age),
那么redis-server在接收到命令的时候会按照顺序先后执行;A和B服务分别向redis-server发送了一条指令
redsi.call(&apos;get&apos;,age),那么redis-server也会按照接收到指令的顺序阻塞执行
</code></pre><h5 id="2-lua原子特性"><a href="#2-lua原子特性" class="headerlink" title="2.lua原子特性"></a>2.lua原子特性</h5><pre><code>redis2.6版本以后,内置了lua脚本的运行环境,默认用eval命令执行;我之所以用到redis执行lua脚本来批量执行redis指令操作,
最大原因是lua脚本被redis执行的时候,能够
保证原子特性(也就是中途不会存在类似java多线程下的cpu时间被剥夺导致挂起),这样的话就能保证数据变更的可靠性和一致性.
</code></pre><h4 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h4><pre><code>常用的扣减操作是service层操作数据库执行update Stock set stock = stock - ? where id = ?
</code></pre><h4 id="存在问题"><a href="#存在问题" class="headerlink" title="存在问题"></a>存在问题</h4><pre><code>单线程一切都运行正常,但是多线程情况下出现数据不一致问题,两个线程在同一个stock基础上进行不同的扣减,
导致后者覆盖前者
</code></pre><h4 id="案例分析"><a href="#案例分析" class="headerlink" title="案例分析"></a>案例分析</h4><pre><code>两个线程A和B同时查到库存为5,A执行操作update Stock set stock = stock - 2 where id = 1,B执行操作
update Stock set stock = stock - 3 where id = 1,
而操作的结果可能是2或者3,而不是我们期望的0;因为A B两个线程查询的时候stock=5,都是在此数字上扣减,
导致其中一个结果被覆盖,拿到错误的扣减结果,
还有一种情况是,设计往往有容错机制，例如“重试”，如果通过扣减接口来修改库存，在重试时，可能会
得到错误的数据，导致重复扣减;
重试导致错误的根本原因，是因为“扣减”操作是一个非幂等的操作，不能够重复执行，改成设置操作则不会
有这个问题
</code></pre><h4 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h4><pre><code>把库存放到redis缓存中,在多线程场景下,让各个服务去检查和修改缓存中的库存量,如果redis中修改成功,
再把数据变更落地,把库存扣减持久化到数据库层;根据上述redis和lua特性,每次请求调用过来扣减库存,
都是去使用redis执行lua脚本去做原子操作检查和修改缓存中的库存;具体看代码分析.
</code></pre><h4 id="以下是代码和并发测试"><a href="#以下是代码和并发测试" class="headerlink" title="以下是代码和并发测试"></a>以下是代码和并发测试</h4><h5 id="1-数据库表依赖上一篇"><a href="#1-数据库表依赖上一篇" class="headerlink" title="1.数据库表依赖上一篇"></a>1.数据库表依赖上一篇</h5><h5 id="2-编写接口及实现"><a href="#2-编写接口及实现" class="headerlink" title="2.编写接口及实现"></a>2.编写接口及实现</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div></pre></td><td class="code"><pre><div class="line">@Override</div><div class="line">public StockResp deductStockV5(StockReq req) &#123;</div><div class="line">	StockResp resp = new StockResp();</div><div class="line">	long stockId = req.getId();</div><div class="line">	Jedis jedis = null;</div><div class="line">	long result = 0;</div><div class="line">	Calendar cal = Calendar.getInstance();</div><div class="line">	try &#123;</div><div class="line">		//查询实际库存</div><div class="line">		Stock stock = this.stockDao.queryByPrimaryKey(req.getId());</div><div class="line">		if(null == stock) &#123;</div><div class="line">			return resp.error(&quot;不存在&quot;);</div><div class="line">		&#125;</div><div class="line">		//获取redis连接</div><div class="line">		jedis = jedisPool.getResource();</div><div class="line">		List&lt;String&gt; keys = new ArrayList&lt;&gt;(1);</div><div class="line">		keys.add(CACHE_STOCK_WAITING_FOR_DEDUCT_PREFIX + stockId);</div><div class="line">		List&lt;String&gt; args = new ArrayList&lt;&gt;(1);</div><div class="line">		args.add(req.getNeedDeduct() + &quot;&quot;);</div><div class="line">		args.add(stock.getStock() + &quot;&quot;);</div><div class="line">		String deductLuaScript = **buildLuaDeductScript()**;</div><div class="line">		//执行lua脚本</div><div class="line">		result = Long.parseLong(jedis.eval(deductLuaScript, keys, args) + &quot;&quot;);</div><div class="line">		if(result &lt; 0) &#123;//库存不足</div><div class="line">			return resp.error(&quot;库存不足&quot;);</div><div class="line">		&#125;</div><div class="line">		stock.setStock((int)result);</div><div class="line">		stock.setUpdateTime(cal.getTime());</div><div class="line">		this.stockDao.update(stock);</div><div class="line">	&#125; catch (Exception e) &#123;</div><div class="line">		//获取连接失败,或者其他异常,抛出去,用来终止程序</div><div class="line">		throw new ServiceRuntimeException(&quot;异常&quot;,e);</div><div class="line">	&#125; finally &#123;</div><div class="line">		IOUtils.closeQuietly(jedis);</div><div class="line">	&#125;</div><div class="line">	return resp;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>以下是lua脚本
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">private String buildLuaDeductScript() &#123;</div><div class="line">	StringBuilder lua = new StringBuilder();</div><div class="line">	lua.append(&quot;\nlocal c&quot;);</div><div class="line">	//KEYS[1]是keys的第一个参数,</div><div class="line">	//ARGV[1]是args的第一个额参数</div><div class="line">	//setnx是如果是不存在该key时才会set成功</div><div class="line">	lua.append(&quot;\nredis.call(&apos;setnx&apos;,KEYS[1],ARGV[1])&quot;);</div><div class="line">	//获取缓存中库存</div><div class="line">	lua.append(&quot;\nc = redis.call(&apos;get&apos;,KEYS[1])&quot;);</div><div class="line">	//判断缓存库存是否小于需要扣减的数量</div><div class="line">	lua.append(&quot;\nif tonumber(c) &lt; tonumber(ARGV[2]) then&quot;);</div><div class="line">	//c=-1表示扣减失败</div><div class="line">	lua.append(&quot;\nc = -1&quot;);</div><div class="line">	lua.append(&quot;\nelse&quot;);</div><div class="line">	//库存足额情况下,把库存扣减</div><div class="line">	lua.append(&quot;\nc = redis.call(&apos;decrby&apos;,KEYS[1],ARGV[1])&quot;);</div><div class="line">	lua.append(&quot;\nend&quot;);</div><div class="line">	lua.append(&quot;\nreturn c;&quot;);</div><div class="line">	return lua.toString();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h5 id="3-单元测试"><a href="#3-单元测试" class="headerlink" title="3.单元测试"></a>3.单元测试</h5><pre><code>单个线程操作
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line">@Test</div><div class="line">public void testDeductStockConcurrentV5() &#123;</div><div class="line">	int threadNum = 20;</div><div class="line">	StockReq req = new StockReq();</div><div class="line">	req.setId(2L);</div><div class="line">	req.setNeedDeduct(3);</div><div class="line">	BlockingQueue&lt;Future&lt;StockResp&gt;&gt; queue = new ArrayBlockingQueue&lt;&gt;(threadNum);</div><div class="line"></div><div class="line">	Future&lt;StockResp&gt; stockTask = null;</div><div class="line">	for (int i = 0; i &lt; threadNum; i++) &#123;</div><div class="line">		stockTask = executors.submit(new DeductStockV5Task(req, stockService));</div><div class="line">		try &#123;</div><div class="line">			queue.put(stockTask);</div><div class="line">		&#125; catch (InterruptedException e) &#123;</div><div class="line">			LOGGER.error(&quot;&quot;, e);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	List&lt;StockResp&gt; list = new ArrayList&lt;&gt;(queue.size());</div><div class="line">	while (!queue.isEmpty()) &#123;</div><div class="line">		try &#123;</div><div class="line">			list.add(queue.take().get(10, TimeUnit.SECONDS));</div><div class="line">		&#125; catch (Exception e) &#123;</div><div class="line">			LOGGER.error(&quot;&quot;, e);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	if (!list.isEmpty()) &#123;</div><div class="line">		for (int i = 0, size = list.size(); i &lt; size; i++) &#123;</div><div class="line">			LOGGER.info(&quot;响应:&#123;&#125;&quot;, JSON.toJSONString(list.get(i)));</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	// this.stockService.deductStock(req);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<pre><code>并发操作
</code></pre><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div></pre></td><td class="code"><pre><div class="line">/**</div><div class="line"> * 测试并发扣减库存操作线程V5</div><div class="line"> * </div><div class="line"> * @author Typhoon</div><div class="line"> * @date 2017-07-12 16:44 Tuesday</div><div class="line"> * @since V1.3.0</div><div class="line"> */</div><div class="line">class DeductStockV5Task implements Callable&lt;StockResp&gt; &#123;</div><div class="line"></div><div class="line">	private StockReq req;</div><div class="line"></div><div class="line">	private StockService stockService;</div><div class="line"></div><div class="line">	public DeductStockV5Task(StockReq req, StockService stockService) &#123;</div><div class="line">		super();</div><div class="line">		this.req = req;</div><div class="line">		this.stockService = stockService;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public StockReq getReq() &#123;</div><div class="line">		return req;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public void setReq(StockReq req) &#123;</div><div class="line">		this.req = req;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public StockService getStockService() &#123;</div><div class="line">		return stockService;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public void setStockService(StockService stockService) &#123;</div><div class="line">		this.stockService = stockService;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	@Override</div><div class="line">	public StockResp call() throws Exception &#123;</div><div class="line"></div><div class="line">		LOGGER.info(&quot;当前线程:&#123;&#125;&quot;, Thread.currentThread().getName());</div><div class="line"></div><div class="line">		try &#123;</div><div class="line">			Thread.sleep(1 * 1000);// 休眠3秒</div><div class="line"></div><div class="line">			StockResp resp = this.stockService.deductStockV5(req);</div><div class="line">			LOGGER.info(&quot;当前线程:&#123;&#125;,扣减库存响应:&#123;&#125;&quot;, Thread.currentThread().getName(), JSON.toJSONString(resp));</div><div class="line">			return resp;</div><div class="line">		&#125; catch (Exception e) &#123;</div><div class="line">			LOGGER.error(&quot;扣减操作异常&quot;, e);</div><div class="line">			return null;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="用20个线程跑了多次-状态良好-欢迎各位大佬指点和拍砖"><a href="#用20个线程跑了多次-状态良好-欢迎各位大佬指点和拍砖" class="headerlink" title="用20个线程跑了多次,状态良好,欢迎各位大佬指点和拍砖"></a>用20个线程跑了多次,状态良好,欢迎各位大佬指点和拍砖</h4>  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/typhoon/categories/案例分析/">案例分析</a>
</div>


  <div class="article-tags">
  
  <span></span> <a href="/typhoon/tags/并发/">并发</a>
  </div>

</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://scorpioaeolus.oschina.io/2017/07/12/并发扣减库存方案二/" data-title="并发扣减库存方案二 | Typhoon&#39;s code space" data-tsina="null" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/typhoon/2017/07/15/springmvc统一异常拦截/" title="springmvc统一异常拦截方式">
  <strong>上一篇：</strong><br/>
  <span>
  springmvc统一异常拦截方式</span>
</a>
</div>


<div class="next">
<a href="/typhoon/2017/07/11/并发扣减库存方案一/"  title="并发扣减库存方案一">
 <strong>下一篇：</strong><br/> 
 <span>并发扣减库存方案一
</span>
</a>
</div>

</nav>

	


</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-redis阻塞操作"><span class="toc-number">1.</span> <span class="toc-text">1.redis阻塞操作</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-lua原子特性"><span class="toc-number">2.</span> <span class="toc-text">2.lua原子特性</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#背景"><span class="toc-number"></span> <span class="toc-text">背景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#存在问题"><span class="toc-number"></span> <span class="toc-text">存在问题</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#案例分析"><span class="toc-number"></span> <span class="toc-text">案例分析</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#解决方案"><span class="toc-number"></span> <span class="toc-text">解决方案</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#以下是代码和并发测试"><span class="toc-number"></span> <span class="toc-text">以下是代码和并发测试</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-数据库表依赖上一篇"><span class="toc-number">1.</span> <span class="toc-text">1.数据库表依赖上一篇</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-编写接口及实现"><span class="toc-number">2.</span> <span class="toc-text">2.编写接口及实现</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-单元测试"><span class="toc-number">3.</span> <span class="toc-text">3.单元测试</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#用20个线程跑了多次-状态良好-欢迎各位大佬指点和拍砖"><span class="toc-number"></span> <span class="toc-text">用20个线程跑了多次,状态良好,欢迎各位大佬指点和拍砖</span></a>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/typhoon/categories/dubbo/" title="dubbo">dubbo<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java性能优化/" title="java性能优化">java性能优化<sup>17</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/java源码分析/" title="java源码分析">java源码分析<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/motan/" title="motan">motan<sup>2</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/spring/" title="spring">spring<sup>11</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springboot/" title="springboot">springboot<sup>28</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/springmvc/" title="springmvc">springmvc<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/容器/" title="容器">容器<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/工具/" title="工具">工具<sup>7</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/性能优化/" title="性能优化">性能优化<sup>5</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/架构/" title="架构">架构<sup>8</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/案例分析/" title="案例分析">案例分析<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/缓存/" title="缓存">缓存<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
		  
		
		  
			<li><a href="/typhoon/categories/面试题/" title="面试题">面试题<sup>1</sup></a></li>
		  
		
		</ul>
</div>


  
<div class="tagslist">
	<p class="asidetitle">Tags</p>
		<ul class="clearfix">
		
			
				<li><a href="/typhoon/tags/springboot/" title="springboot">springboot<sup>28</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/java性能优化/" title="java性能优化">java性能优化<sup>9</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/限流/" title="限流">限流<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring5/" title="Spring5">Spring5<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/设计模式/" title="设计模式">设计模式<sup>3</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/案例分析/" title="案例分析">案例分析<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/性能优化/" title="性能优化">性能优化<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/Spring/" title="Spring">Spring<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo/" title="dubbo">dubbo<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/分页/" title="分页">分页<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/并发/" title="并发">并发<sup>2</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/异常拦截/" title="异常拦截">异常拦截<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo分布式事务/" title="dubbo分布式事务">dubbo分布式事务<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/自带图片/" title="自带图片">自带图片<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/svn导出mvn项目/" title="svn导出mvn项目">svn导出mvn项目<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/dubbo过滤器/" title="dubbo过滤器">dubbo过滤器<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/排序性能对比/" title="排序性能对比">排序性能对比<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/ListenableFuture/" title="ListenableFuture">ListenableFuture<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/PropertyChangeListener/" title="PropertyChangeListener">PropertyChangeListener<sup>1</sup></a></li>
			
		
			
				<li><a href="/typhoon/tags/jdbcTemplate高可用/" title="jdbcTemplate高可用">jdbcTemplate高可用<sup>1</sup></a></li>
			
		
		</ul>
</div>


  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=null&verifier=b3593ceb&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m a java coder. <br/>
			This is my blog,believe it or not.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
		<a href="mailto:ScorpioAeolus@163.com" target="_blank" class="icon-email" title="Email Me"></a>
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2019 
		
		<a href="/typhoon/about" target="_blank" title="typhoon">typhoon</a>
		
		
		</p>
</div>
</footer>
    <script src="/typhoon/js/jquery-2.0.3.min.js"></script>
<script src="/typhoon/js/jquery.imagesloaded.min.js"></script>
<script src="/typhoon/js/gallery.js"></script>
<script src="/typhoon/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>









<link rel="stylesheet" href="/typhoon/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/typhoon/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/typhoon/img/scrollup.png"/></a>
	</div>
	<script src="/typhoon/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
